package com.dong.sortingAlgorithm;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/*
冒泡排序算法(O(n^2))
 */
public class Bubblealgorithm {
    public static void main(String[] args) {
        int arr[] = new int[80000];
        for (int i = 0; i < 80000; i++) {
            arr[i]= (int)(Math.random()*1000);
        }
        //开始时间
        Date date1 = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time1 = simpleDateFormat.format(date1);
        System.out.println("开始时间为"+time1);

        bubble2(arr);

        //排序完时间
        Date date2 = new Date();
        String time2 = simpleDateFormat.format(date2);
        System.out.println("排序后得时间为"+time2);
    }

    //从小到大
    public static void bubble(int[] arrays){
        boolean flag = false; //用来优化，标识变量，表示是否进行过交换
        int length = arrays.length;
        int temps =0;
        //外循环为走的次数
        for (int i = 0; i < length-1; i++) {
            //内循环为比较的次数
            for (int j = 0; j < length-1-i; j++) {
                if (arrays[j]>arrays[j+1]){
                    flag = true;
                    temps = arrays[j+1];
                    arrays[j+1] = arrays[j];
                    arrays[j] =temps;
                }
            }
            if (!flag){
                break;
            }else {
                flag = false; //重置flag进行下次排序
            }
        };

    }

    //从大到小
    public static void bubble2(int arrays[]){
        int length = arrays.length;
        int temps =0;
        int k = 0;
        //外循环为走的次数
        for (int i = 0; i < length-1; i++) {
            //内循环为比较的次数
            for (int j = 0; j < length-1-i; j++) {
                if (arrays[j]<arrays[j+1]){
                    k++;
                    temps = arrays[j+1];
                    arrays[j+1] = arrays[j];
                    arrays[j] =temps;
                }
            }
        }
        System.out.println(k);
    }
    


}
